use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{RwLock, mpsc};
use tokio::time::{interval, Instant};
use tracing::{info, error, warn, debug};

use crate::config::ConfigManager;
use crate::collector::CollectionTask;
use crate::error::{Result, ModbusCollectorError};

/// 任务调度器
#[derive(Debug)]
pub struct TaskScheduler {
    tasks: Arc<RwLock<HashMap<String, CollectionTask>>>,
    task_sender: mpsc::UnboundedSender<CollectionTask>,
    config_manager: ConfigManager,
}

impl TaskScheduler {
    pub fn new(
        config_manager: ConfigManager,
        task_sender: mpsc::UnboundedSender<CollectionTask>,
    ) -> Self {
        Self {
            tasks: Arc::new(RwLock::new(HashMap::new())),
            task_sender,
            config_manager,
        }
    }
    
    /// 启动调度器
    pub async fn start(&self) -> Result<()> {
        info!("Starting task scheduler");
        
        // 初始化任务
        self.initialize_tasks().await?;
        
        // 启动调度循环
        let tasks = self.tasks.clone();
        let sender = self.task_sender.clone();
        
        tokio::spawn(async move {
            let mut ticker = interval(Duration::from_millis(100)); // 100ms检查一次
            
            loop {
                ticker.tick().await;
                let now = Instant::now();
                
                let tasks_to_execute = {
                    let mut tasks_guard = tasks.write().await;
                    let mut to_execute = Vec::new();
                    
                    for (_, task) in tasks_guard.iter_mut() {
                        if task.should_execute(now) {
                            task.update_execution_time(now);
                            to_execute.push(task.clone());
                        }
                    }
                    
                    to_execute
                };
                
                // 发送需要执行的任务
                for task in tasks_to_execute {
                    if let Err(e) = sender.send(task.clone()) {
                        error!("Failed to send task {}: {}", task.task_id, e);
                    } else {
                        debug!("Scheduled task {} for device {}", task.task_id, task.device_id);
                    }
                }
            }
        });
        
        info!("Task scheduler started");
        Ok(())
    }
    
    /// 初始化任务
    async fn initialize_tasks(&self) -> Result<()> {
        info!("Initializing collection tasks");
        
        let devices = self.config_manager.get_devices().await;
        let mut task_map = HashMap::new();
        
        for (device_id, device_config) in devices {
            if !device_config.enable {
                info!("Device {} is disabled, skipping", device_id);
                continue;
            }
            
            let points = self.config_manager.get_device_points(&device_id).await;
            if points.is_empty() {
                warn!("No points configured for device {}, skipping", device_id);
                continue;
            }
            
            let task = CollectionTask::new(device_config, points);
            info!("Created collection task {} for device {} with {} points", 
                  task.task_id, device_id, task.points.len());
            
            task_map.insert(device_id.clone(), task);
        }
        
        *self.tasks.write().await = task_map;
        info!("Initialized {} collection tasks", self.tasks.read().await.len());
        
        Ok(())
    }
    
    /// 重新加载任务配置
    pub async fn reload_tasks(&self) -> Result<()> {
        info!("Reloading collection tasks");
        self.initialize_tasks().await
    }
    
    /// 获取任务状态
    pub async fn get_task_status(&self) -> HashMap<String, TaskStatus> {
        let tasks = self.tasks.read().await;
        let mut status_map = HashMap::new();
        
        for (device_id, task) in tasks.iter() {
            let status = TaskStatus {
                task_id: task.task_id.clone(),
                device_id: device_id.clone(),
                enabled: task.enabled,
                interval_ms: task.interval_ms,
                last_execution: task.last_execution,
                points_count: task.points.len(),
            };
            status_map.insert(device_id.clone(), status);
        }
        
        status_map
    }
    
    /// 启用/禁用任务
    pub async fn set_task_enabled(&self, device_id: &str, enabled: bool) -> Result<()> {
        let mut tasks = self.tasks.write().await;
        if let Some(task) = tasks.get_mut(device_id) {
            task.enabled = enabled;
            info!("Task for device {} {}", device_id, if enabled { "enabled" } else { "disabled" });
            Ok(())
        } else {
            Err(ModbusCollectorError::Config(
                format!("Task not found for device: {}", device_id)
            ))
        }
    }
}

/// 任务状态
#[derive(Debug, Clone)]
pub struct TaskStatus {
    pub task_id: String,
    pub device_id: String,
    pub enabled: bool,
    pub interval_ms: u64,
    pub last_execution: Option<Instant>,
    pub points_count: usize,
}